<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


/**
 * qq jiankong data interface
 * public functions:
 *    upload : upload user sport data from temp tables
 *    create : pre-create user sport data into temp tables
 *
 * error log path  : /../logs
 */
class Qqjiankang extends CI_Controller{

    private $current_info=array();             // current handle user info
    public  $invalid_access_token_tid = array();   // store invalid access_token user id
    public  $rows_destory = array();              // rows over time or invalid or upload success, destory it!
    // public  $update_mark_tid = array();           // which user need to update lastupdatemark
    public  $upload_error = array();               // qqhealth upload error infos
    private $log_file;                            // logs_file 

    // create actions
    public $actions = array();


    // handle by user 
    public $tid;
    public $openid;
    public $appid;

    public function __construct(){
            parent::__construct();
            $this->load->helper("common");
              $this->load->helper('date');
              date_default_timezone_set("PRC");


    }



/**
 * do upload by user
 */
public function do_upload_bg($user,$data,$type){
      if(empty($data)) {
            json_return(true,"already up-today" );
      }
    # create our client object
    $gmclient= new GearmanClient();

    # add the default server (localhost)
    $gmclient->addServer();

    # run reverse client in the background
    // $job_handle = $gmclient->doBackground("reverse", $token);

    $params = serialize(array('user'=>$user,'data'=>$data,'type'=>$type));
    $job_handle = $gmclient->doBackground("health_bg_upload", $params);

    if ($gmclient->returnCode() != GEARMAN_SUCCESS)
    {
      json_return(false,"system busy......");
      exit;
    }

      // json_return(true,"action sended!");
      json_return(true,"uploading......please reflash later" );

}
   /**************************************************************************/
   /**************************************************************************/
   /*****************************1 upload action *********************************/
   /**************************************************************************/
   /**************************************************************************/

   /**
    * [upload upload user sport data from temp tables]
    * @return [type] [description]
    */
    public function upload(){
        $token = $this->input->post('token');
        //  upload appoitment user data
        if($token){
            // check join
            $this->_check_is_join($token);
            // get upload data by user
            $data = $this->_do_upload_by_user();

        }else{
            // no token , handle automatically
            // $this->_do_upload_by_auto();
            gearman_client();

        }

    }

   /**
    * handle by user
    */
    private function _do_upload_by_user(){
        $actions = array_keys($this->config->item('health_type'));
        foreach ($actions as $type) {

            // handle one user
            $this->_upload_one_user($type);

        }


    }


/*********************************************************************************/
    private function _upload_one_user($type,$user=null){
   
            // order
            $mark = $this->_mark($type);
            // status
            $status = $this->_status($type);

            
            $user = !is_null($user) ? $user : $this->user;

            // check api status for type
            if($user[$status] != 1) return false;

            if(!$user) return false;
            // check status
            if( $user[$status] != 1) {
                return false;
            }

            // check openid
            $this->openid = get_open_id($user['access_token']);
            if(!$this->openid){
                echo "invalid access_token tid:".$user['tid']."\r\n";
                // $this->rows_destory[] = $v['id'];
                continue;
            }

            // create each user's temp data
            $table = "user_data";
            $this->load->model($table);
            $db = $this->$table->db;
            $sql = "select data from {$table} ";
            $sql .= "where tid=".$user['tid'] ;
            $sql .=" and to_char(date,'yyyy-mm-dd') > to_char(to_timestamp(".$user[$mark]."),'yyyy-mm-dd') ";
            $sql .= "order by date asc ";
            $rs = $db->query($sql)->result_array();
            
            // if no $result or count $result less than limit $num, then set status = 0 (no update-data any more); 
            if(!$rs){
                $this->load->model("user_qqhealth_api");
                $qqapi_db = $this->user_qqhealth_api->db;
                $qqapi_db->where("tid",$user['tid']);
                $qqapi_db->update('user_qqhealth_api',array($status=>0));
                // var_dump($rs);
            }
            // var_dump($rs);die;
            // create temp datas
            $this->do_upload_bg($user,$rs,$type);
    }

    private function _check_is_join($token){
        //check token 
        $this->load->model('user_token');
        $rs = $this->user_token->checkToken($token);
        // var_dump($rs);die;
        if(!$rs) json_return(false,"no access allow");
        // check is_join
        $this->load->model('user_qqhealth_api');
        $is_join = $this->user_qqhealth_api->get_is_join($rs['tid']);

        if(!$is_join || $is_join['is_join'] != 1) json_return(false,"you don't join this function");

        $this->user = $is_join;
    }

/***********************************************************************************************/
/***********************************************************************************************/
/***********************************************************************************************/
/***********************************************************************************************/
/***********************************************************************************************/



  private function _get_upload_url($table){
    $name = "report_" . str_replace("user_qqupload_temp_", "", $table)  . "_url";
    return $this->config->item($name) ;
  }

  private function _get_upload_fields($table){
        $name = "fields_report_" . str_replace("user_qqupload_temp_", "", $table) ;
        return $this->config->item($name);
  }
   
   private function _mark($type){
        switch ($type) {
            case 'steps':
                    return 'lastupdatemark_step';
                break;
            case 'sleep':
                    return 'lastupdatemark_sleep';
                break;
            
            default:
                # code...
                break;
        }
   }

   private function _status($type){
        switch ($type) {
            case 'steps':
                    return 'status_step';
                break;
            case 'sleep':
                    return 'status_sleep';
                break;
            
            default:
                # code...
                break;
        }
   }


} // class end
 ?>